home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / usr / bin / lwp-request < prev    next >
Encoding:
Text File  |  2006-06-19  |  14.4 KB  |  549 lines

  1. #!/usr/bin/perl -w
  2.  
  3. eval 'exec /usr/bin/perl -w -S $0 ${1+"$@"}'
  4.     if 0; # not running under some shell
  5.  
  6. # $Id: lwp-request,v 2.7 2005/12/06 12:16:28 gisle Exp $
  7. #
  8. # Simple user agent using LWP library.
  9.  
  10. =head1 NAME
  11.  
  12. lwp-request - Simple command line user agent
  13.  
  14. =head1 SYNOPSIS
  15.  
  16.  lwp-request [-aeEdvhx] [-m method] [-b <base URL>] [-t <timeout>]
  17.              [-i <if-modified-since>] [-c <content-type>] [-C <credentials>]
  18.              [-p <proxy-url>] [-o <format>] <url>...
  19.  
  20. =head1 DESCRIPTION
  21.  
  22. This program can be used to send requests to WWW servers and your
  23. local file system. The request content for POST and PUT
  24. methods is read from stdin.  The content of the response is printed on
  25. stdout.  Error messages are printed on stderr.  The program returns a
  26. status value indicating the number of URLs that failed.
  27.  
  28. The options are:
  29.  
  30. =over 4
  31.  
  32. =item -m <method>
  33.  
  34. Set which method to use for the request.  If this option is not used,
  35. then the method is derived from the name of the program.
  36.  
  37. =item -f
  38.  
  39. Force request through, even if the program believes that the method is
  40. illegal.  The server might reject the request eventually.
  41.  
  42. =item -b <uri>
  43.  
  44. This URI will be used as the base URI for resolving all relative URIs
  45. given as argument.
  46.  
  47. =item -t <timeout>
  48.  
  49. Set the timeout value for the requests.  The timeout is the amount of
  50. time that the program will wait for a response from the remote server
  51. before it fails.  The default unit for the timeout value is seconds.
  52. You might append "m" or "h" to the timeout value to make it minutes or
  53. hours, respectively.  The default timeout is '3m', i.e. 3 minutes.
  54.  
  55. =item -i <time>
  56.  
  57. Set the If-Modified-Since header in the request. If I<time> is the
  58. name of a file, use the modification timestamp for this file. If
  59. I<time> is not a file, it is parsed as a literal date. Take a look at
  60. L<HTTP::Date> for recognized formats.
  61.  
  62. =item -c <content-type>
  63.  
  64. Set the Content-Type for the request.  This option is only allowed for
  65. requests that take a content, i.e. POST and PUT.  You can
  66. force methods to take content by using the C<-f> option together with
  67. C<-c>.  The default Content-Type for POST is
  68. C<application/x-www-form-urlencoded>.  The default Content-type for
  69. the others is C<text/plain>.
  70.  
  71. =item -p <proxy-url>
  72.  
  73. Set the proxy to be used for the requests.  The program also loads
  74. proxy settings from the environment.  You can disable this with the
  75. C<-P> option.
  76.  
  77. =item -H <header>
  78.  
  79. Send this HTTP header with each request. You can specify several, e.g.:
  80.  
  81.     lwp-request \
  82.     -H 'Referer: http://other.url/' \
  83.     -H 'Host: somehost' \
  84.     http://this.url/
  85.  
  86. =item -C <username>:<password>
  87.  
  88. Provide credentials for documents that are protected by Basic
  89. Authentication.  If the document is protected and you did not specify
  90. the username and password with this option, then you will be prompted
  91. to provide these values.
  92.  
  93. =back
  94.  
  95. The following options controls what is displayed by the program:
  96.  
  97. =over 4
  98.  
  99. =item -u
  100.  
  101. Print request method and absolute URL as requests are made.
  102.  
  103. =item -U
  104.  
  105. Print request headers in addition to request method and absolute URL.
  106.  
  107. =item -s
  108.  
  109. Print response status code.  This option is always on for HEAD requests.
  110.  
  111. =item -S
  112.  
  113. Print response status chain. This shows redirect and authorization
  114. requests that are handled by the library.
  115.  
  116. =item -e
  117.  
  118. Print response headers.  This option is always on for HEAD requests.
  119.  
  120. =item -d
  121.  
  122. Do B<not> print the content of the response.
  123.  
  124. =item -o <format>
  125.  
  126. Process HTML content in various ways before printing it.  If the
  127. content type of the response is not HTML, then this option has no
  128. effect.  The legal format values are; I<text>, I<ps>, I<links>,
  129. I<html> and I<dump>.
  130.  
  131. If you specify the I<text> format then the HTML will be formatted as
  132. plain latin1 text.  If you specify the I<ps> format then it will be
  133. formatted as Postscript.
  134.  
  135. The I<links> format will output all links found in the HTML document.
  136. Relative links will be expanded to absolute ones.
  137.  
  138. The I<html> format will reformat the HTML code and the I<dump> format
  139. will just dump the HTML syntax tree.
  140.  
  141. Note that the C<HTML-Tree> distribution needs to be installed for this
  142. option to work.  In addition the C<HTML-Format> distribution needs to
  143. be installed for I<-o text> or I<-o ps> to work.
  144.  
  145. =item -v
  146.  
  147. Print the version number of the program and quit.
  148.  
  149. =item -h
  150.  
  151. Print usage message and quit.
  152.  
  153. =item -x
  154.  
  155. Extra debugging output.
  156.  
  157. =item -a
  158.  
  159. Set text(ascii) mode for content input and output.  If this option is not
  160. used, content input and output is done in binary mode.
  161.  
  162. =back
  163.  
  164. Because this program is implemented using the LWP library, it will
  165. only support the protocols that LWP supports.
  166.  
  167. =head1 SEE ALSO
  168.  
  169. L<lwp-mirror>, L<LWP>
  170.  
  171. =head1 COPYRIGHT
  172.  
  173. Copyright 1995-1999 Gisle Aas.
  174.  
  175. This library is free software; you can redistribute it and/or
  176. modify it under the same terms as Perl itself.
  177.  
  178. =head1 AUTHOR
  179.  
  180. Gisle Aas <gisle@aas.no>
  181.  
  182. =cut
  183.  
  184. $progname = $0;
  185. $progname =~ s,.*[\\/],,;  # use basename only
  186. $progname =~ s/\.\w*$//;   # strip extension, if any
  187.  
  188. $VERSION = sprintf("%d.%02d", q$Revision: 2.7 $ =~ /(\d+)\.(\d+)/);
  189.  
  190.  
  191. require LWP;
  192. require LWP::Debug;
  193.  
  194. use URI;
  195. use URI::Heuristic qw(uf_uri);
  196.  
  197. use HTTP::Status qw(status_message);
  198. use HTTP::Date qw(time2str str2time);
  199.  
  200.  
  201. # This table lists the methods that are allowed.  It should really be
  202. # a superset for all methods supported for every scheme that may be
  203. # supported by the library.  Currently it might be a bit too HTTP
  204. # specific.  You might use the -f option to force a method through.
  205. #
  206. # "" = No content in request, "C" = Needs content in request
  207. #
  208. %allowed_methods = (
  209.     GET        => "",
  210.     HEAD       => "",
  211.     POST       => "C",
  212.     PUT        => "C",
  213.     DELETE     => "",
  214.     TRACE      => "",
  215.     OPTIONS    => "",
  216. );
  217.  
  218.  
  219. # We make our own specialization of LWP::UserAgent that asks for
  220. # user/password if document is protected.
  221. {
  222.     package RequestAgent;
  223.     @ISA = qw(LWP::UserAgent);
  224.  
  225.     sub new
  226.     { 
  227.     my $self = LWP::UserAgent::new(@_);
  228.     $self->agent("lwp-request/$main::VERSION");
  229.     $self;
  230.     }
  231.  
  232.     sub get_basic_credentials
  233.     {
  234.     my($self, $realm, $uri) = @_;
  235.     if ($main::options{'C'}) {
  236.         return split(':', $main::options{'C'}, 2);
  237.     }
  238.     elsif (-t) {
  239.         my $netloc = $uri->host_port;
  240.         print "Enter username for $realm at $netloc: ";
  241.         my $user = <STDIN>;
  242.         chomp($user);
  243.         return (undef, undef) unless length $user;
  244.         print "Password: ";
  245.         system("stty -echo");
  246.         my $password = <STDIN>;
  247.         system("stty echo");
  248.         print "\n";  # because we disabled echo
  249.         chomp($password);
  250.         return ($user, $password);
  251.     }
  252.     else {
  253.         return (undef, undef)
  254.     }
  255.     }
  256. }
  257.  
  258. $method = uc(lc($progname) eq "lwp-request" ? "GET" : $progname);
  259.  
  260. # Parse command line
  261. use Getopt::Long;
  262.  
  263. my @getopt_args = (
  264.     'a', # content i/o in text(ascii) mode
  265.     'm=s', # set method
  266.     'f', # make request even if method is not in %allowed_methods
  267.     'b=s', # base url
  268.     't=s', # timeout
  269.     'i=s', # if-modified-since
  270.     'c=s', # content type for POST
  271.     'C=s', # credentials for basic authorization
  272.     'H=s@', # extra headers, form "Header: value string"
  273.     #
  274.     'u', # display method, URL and headers of request
  275.     'U', # display request headers also
  276.     's', # display status code
  277.     'S', # display whole chain of status codes
  278.     'e', # display response headers (default for HEAD)
  279.     'd', # don't display content
  280.     #
  281.     'h', # print usage
  282.     'v', # print version
  283.     #
  284.     'x', # extra debugging info
  285.     'p=s', # proxy URL
  286.     'P', # don't load proxy setting from environment
  287.     #
  288.     'o=s', # output format
  289. );
  290.  
  291. Getopt::Long::config("noignorecase", "bundling");
  292. unless (GetOptions(\%options, @getopt_args)) {
  293.     usage();
  294. }
  295. if ($options{'v'}) {
  296.     require LWP;
  297.     my $DISTNAME = 'libwww-perl-' . LWP::Version();
  298.     die <<"EOT";
  299. This is lwp-request version $VERSION ($DISTNAME)
  300.  
  301. Copyright 1995-1999, Gisle Aas.
  302.  
  303. This program is free software; you can redistribute it and/or
  304. modify it under the same terms as Perl itself.
  305. EOT
  306. }
  307.  
  308. usage() if $options{'h'} || !@ARGV;
  309.  
  310. LWP::Debug::level('+') if $options{'x'};
  311.  
  312. # Create the user agent object
  313. $ua = RequestAgent->new;
  314.  
  315. # Load proxy settings from *_proxy environment variables.
  316. $ua->env_proxy unless $options{'P'};
  317.  
  318. $method = uc($options{'m'}) if defined $options{'m'};
  319.  
  320. if ($options{'f'}) {
  321.     if ($options{'c'}) {
  322.         $allowed_methods{$method} = "C";  # force content
  323.     }
  324.     else {
  325.         $allowed_methods{$method} = "";
  326.     }
  327. }
  328. elsif (!defined $allowed_methods{$method}) {
  329.     die "$progname: $method is not an allowed method\n";
  330. }
  331.  
  332. if ($method eq "HEAD") {
  333.     $options{'s'} = 1;
  334.     $options{'e'} = 1 unless $options{'d'};
  335.     $options{'d'} = 1;
  336. }
  337.  
  338. if (defined $options{'t'}) {
  339.     $options{'t'} =~ /^(\d+)([smh])?/;
  340.     die "$progname: Illegal timeout value!\n" unless defined $1;
  341.     $timeout = $1;
  342.     if (defined $2) {
  343.         $timeout *= 60   if $2 eq "m";
  344.         $timeout *= 3600 if $2 eq "h";
  345.     }
  346.     $ua->timeout($timeout);
  347. }
  348.  
  349. if (defined $options{'i'}) {
  350.     if (-e $options{'i'}) {
  351.         $time = (stat _)[9];
  352.     }
  353.     else {
  354.         $time = str2time($options{'i'});
  355.         die "$progname: Illegal time syntax for -i option\n"
  356.             unless defined $time;
  357.     }
  358.     $options{'i'} = time2str($time);
  359. }
  360.  
  361. $content = undef;
  362. if ($allowed_methods{$method} eq "C") {
  363.     # This request needs some content
  364.     unless (defined $options{'c'}) {
  365.         # set default content type
  366.         $options{'c'} = ($method eq "POST") ?
  367.               "application/x-www-form-urlencoded"
  368.             : "text/plain";
  369.     }
  370.     else {
  371.         die "$progname: Illegal Content-type format\n"
  372.             unless $options{'c'} =~ m,^[\w\-]+/[\w\-]+(?:\s*;.*)?$,
  373.     }
  374.     print "Please enter content ($options{'c'}) to be ${method}ed:\n"
  375.         if -t;
  376.     binmode STDIN unless -t or $options{'a'};
  377.     $content = join("", <STDIN>);
  378. }
  379. else {
  380.     die "$progname: Can't set Content-type for $method requests\n"
  381.         if defined $options{'c'};
  382. }
  383.  
  384. # Set up a request.  We will use the same request object for all URLs.
  385. $request = HTTP::Request->new($method);
  386. $request->header('If-Modified-Since', $options{'i'}) if defined $options{'i'};
  387. for my $user_header (@{ $options{'H'} || [] }) {
  388.     my ($header_name, $header_value) = split /:\s*/, $user_header, 2;
  389.     $request->header($header_name, $header_value);
  390.     $ua->agent($header_value) if lc($header_name) eq "user-agent"; # Ugh!
  391. }
  392. #$request->header('Accept', '*/*');
  393. if ($options{'c'}) { # will always be set for request that wants content
  394.     $request->header('Content-Type', $options{'c'});
  395.     $request->header('Content-Length', length $content);  # Not really needed
  396.     $request->content($content);
  397. }
  398.  
  399. $errors = 0;
  400.  
  401. # Ok, now we perform the requests, one URL at a time
  402. while ($url = shift) {
  403.     # Create the URL object, but protect us against bad URLs
  404.     eval {
  405.     if ($url =~ /^\w+:/ || $options{'b'}) {  # is there any scheme specification
  406.         $url = URI->new($url, $options{'b'});
  407.         $url = $url->abs($options{'b'}) if $options{'b'};
  408.     }
  409.     else {
  410.         $url = uf_uri($url);
  411.         }
  412.     };
  413.     if ($@) {
  414.     $@ =~ s/ at .* line \d+.*//;
  415.     print STDERR $@;
  416.     $errors++;
  417.     next;
  418.     }
  419.  
  420.     $ua->proxy($url->scheme, $options{'p'}) if $options{'p'};
  421.  
  422.     # Send the request and get a response back from the server
  423.     $request->url($url);
  424.     $response = $ua->request($request);
  425.  
  426.     if ($options{'u'} || $options{'U'}) {
  427.         my $url = $response->request->url->as_string;
  428.         print "$method $url\n";
  429.         print $response->request->headers_as_string, "\n" if $options{'U'};
  430.     }
  431.  
  432.     if ($options{'S'}) {
  433.     printResponseChain($response);
  434.     }
  435.     elsif ($options{'s'}) {
  436.         print $response->status_line, "\n";
  437.     }
  438.  
  439.     if ($options{'e'}) {
  440.         # Display headers
  441.         print $response->headers_as_string;
  442.         print "\n";  # separate headers and content
  443.     }
  444.  
  445.     unless ($options{'d'}) {
  446.     if ($options{'o'} &&
  447.         $response->content_type eq 'text/html') {
  448.         eval {
  449.         require HTML::Parse;
  450.         };
  451.         if ($@) {
  452.         if ($@ =~ m,^Can't locate HTML/Parse.pm in \@INC,) {
  453.             die "The HTML-Tree distribution need to be installed for the -o option to be used.\n";
  454.         }
  455.         else {
  456.             die $@;
  457.         }
  458.         }
  459.         my $html = HTML::Parse::parse_html($response->content);
  460.         {
  461.         $options{'o'} eq 'ps' && do {
  462.             require HTML::FormatPS;
  463.             my $f = HTML::FormatPS->new;
  464.             print $f->format($html);
  465.             last;
  466.         };
  467.         $options{'o'} eq 'text' && do {
  468.             require HTML::FormatText;
  469.             my $f = HTML::FormatText->new;
  470.             print $f->format($html);
  471.             last;
  472.         };
  473.         $options{'o'} eq 'html' && do {
  474.             print $html->as_HTML;
  475.             last;
  476.         };
  477.         $options{'o'} eq 'links' && do {
  478.             my $base = $response->base;
  479.             $base = $options{'b'} if $options{'b'};
  480.             for ( @{ $html->extract_links } ) {
  481.             my($link, $elem) = @$_;
  482.             my $tag = uc $elem->tag;
  483.             $link = URI->new($link)->abs($base)->as_string;
  484.             print "$tag\t$link\n";
  485.             }
  486.             last;
  487.         };
  488.         $options{'o'} eq 'dump' && do {
  489.             $html->dump;
  490.             last;
  491.         };
  492.         # It is bad to not notice this before now :-(
  493.         die "Illegal -o option value ($options{'o'})\n";
  494.         }
  495.     }
  496.     else {
  497.         binmode STDOUT unless $options{'a'};
  498.         print $response->content;
  499.     }
  500.     }
  501.  
  502.     $errors++ unless $response->is_success;
  503. }
  504.  
  505. exit $errors;
  506.  
  507.  
  508. sub printResponseChain
  509. {
  510.     my($response) = @_;
  511.     return unless defined $response;
  512.     printResponseChain($response->previous);
  513.     my $method = $response->request->method;
  514.     my $url = $response->request->url->as_string;
  515.     my $code = $response->code;
  516.     print "$method $url --> ", $response->status_line, "\n";
  517. }
  518.  
  519.  
  520. sub usage
  521. {
  522.     die <<"EOT";
  523. Usage: $progname [-options] <url>...
  524.     -m <method>   use method for the request (default is '$method')
  525.     -f            make request even if $progname believes method is illegal
  526.     -b <base>     Use the specified URL as base
  527.     -t <timeout>  Set timeout value
  528.     -i <time>     Set the If-Modified-Since header on the request
  529.     -c <conttype> use this content-type for POST, PUT, CHECKIN
  530.     -a            Use text mode for content I/O
  531.     -p <proxyurl> use this as a proxy
  532.     -P            don't load proxy settings from environment
  533.     -H <header>   send this HTTP header (you can specify several)
  534.  
  535.     -u            Display method and URL before any response
  536.     -U            Display request headers (implies -u)
  537.     -s            Display response status code
  538.     -S            Display response status chain
  539.     -e            Display response headers
  540.     -d            Do not display content
  541.     -o <format>   Process HTML content in various ways
  542.  
  543.     -v            Show program version
  544.     -h            Print this message
  545.  
  546.     -x            Extra debugging output
  547. EOT
  548. }
  549.